// fdc
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
	"strings"
	"time"

	"github.com/axgle/mahonia"
	"github.com/larspensjo/config"
)

var index int = 0
var (
	configfile = flag.String("ConfigIni", "FormatDataconvert.ini", "ini configfile")
)
var targetName string = "DataConvert.ini"

func main() {
	{
		cfg, err := config.ReadDefault(*configfile)
		if err != nil {
			fmt.Print("no config file")
			targetName = "DataConvert.ini"
		} else {
			if cfg.HasSection("File") {
				//			session, err := cfg.SectionOptions("File")
				//	if err == nil {
				targetName, err = cfg.String("File", "Name")
				if err == nil {
					fmt.Print(targetName)
				} else {
					targetName = "DataConvert.ini"
				}
			}

		}
		//s := "\xb6\xd4\xb6\xc0\xc1\xa2\xd1\xa7\xd4\xba\xbf\xc9\xb3\xd6\xd0\xf8\xb7\xa2\xd5\xb9\xce\xca\xcc\xe2"
		//s:="\xe5\xaf\xb9"
		s := "\345\257\271\345\272\224"
		enc := mahonia.NewDecoder("utf8")
		fmt.Println(enc.ConvertString(s))
		//t:="\xb6\xe4\xb6\xd4"
		t := "\266\324\323\246"
		enc2 := mahonia.NewDecoder("gb18030")
		fmt.Println(enc2.ConvertString(t))
	}
	tt := fmt.Sprintf("%04d%02d%02d_%02d%02d%02d", time.Now().Year(), time.Now().Month(), time.Now().Day(), time.Now().Hour(), time.Now().Minute(), time.Now().Second())
	fmt.Println("time", tt)

	err := os.Rename(targetName, targetName+tt)
	if err != nil {
		fmt.Print(err)
	}
	inFile, err := os.Open(targetName + tt)
	if err != nil {
		fmt.Print("error open file")
		fmt.Scanln()
		return
	}
	defer inFile.Close()

	outFile, err := os.OpenFile(targetName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.ModeType)
	if err != nil {
		fmt.Print("open %s error", targetName)
		fmt.Scanln()
		return
	}
	defer outFile.Close()
	//	outWriter:=bufio.NewWriter(outFile)
	decoder := mahonia.NewDecoder("gb18030")
	inReader := bufio.NewReader(decoder.NewReader(inFile))

	for err == nil || err == io.EOF {
		inLine, err := inReader.ReadString('\n')
		if err == io.EOF {
			fmt.Print("End Of File")
			break
		}
		gbk := mahonia.NewEncoder("gbk")
		strLine := gbk.ConvertString(ProcessLine(inLine))
		outFile.WriteString(strLine)
		outFile.WriteString("\r\n")
		//		outFile.WriteString(inLine+"\r\n")
		//		fmt.Println(inLine)
	}
	fmt.Scanln()
}
func ProcessLine(line string) string {
	strLine := strings.TrimSpace(line)
	if strings.HasPrefix(strLine, "[") && strings.Contains(strLine, "]") {
		index = 0
		return strLine
	}

	if strings.HasPrefix(strings.ToUpper(strLine), "SENTENCE") {
		index = index + 1
		str := strings.SplitAfterN(strLine, "=", 2)
		strLine = fmt.Sprintf("%s%d = %s", "SENTENCE", index, strings.TrimSpace(str[1]))
		//		fmt.Println(strLine)
		//		enc:=mahonia.NewEncoder("")
		//		strLine=enc.ConvertString(strLine)
	}
	return strLine
}
